package com.youthburin.rmp.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youthburin.base.controller.BaseController;
import com.youthburin.base.services.OpLogService;
import com.youthburin.base.util.DwzResponse;
import com.youthburin.base.util.DwzResponseUtils;
import com.youthburin.rmp.enums.RmpOpLogBusiTypeEnum;
import com.youthburin.rmp.enums.RmpOpLogTypeEnum;

@Controller
public class LoginController extends BaseController {
	@Autowired
	@Qualifier("rmpOpLogService")
	private OpLogService opLogService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/login/dialog", method = RequestMethod.GET)
	public String toLogindialog() {
		return "login_dialog";
	}

	@RequestMapping(value = "/login/dialog", method = RequestMethod.POST)
	@ResponseBody
	public DwzResponse logindialog(String username, String password, HttpServletRequest request) {
		AuthenticationToken token = new UsernamePasswordToken(username, password);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
			opLogService.addLog(RmpOpLogTypeEnum.LOGIN.toString(), RmpOpLogBusiTypeEnum.DEFAULT.toString(), username);
		} catch (AuthenticationException e) {
			return DwzResponseUtils.createFailResponse(getMessage("error.login.usernameorpasswordwrong", request));
		}

		return DwzResponseUtils.createSuccessResponse(true);
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}
}
